/*
 * 
 * 
 * 
 */
package com.exp.base.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.ArrayConverter;
import org.apache.commons.beanutils.converters.DateConverter;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.utility.DeepUnwrap;

/**
 * Utils - Freemarker
 * 
 * 
 * 
 */
@SuppressWarnings("unchecked")
public final class FreemarkerUtils {
	private static Configuration configuration = null;

	/**
	 * 不可实例化
	 */
	private FreemarkerUtils() {
	}

	private static void check(){
		if (configuration == null) {
			FreeMarkerConfigurer freeMarkerConfigurer = SpringUtils.getBean("freemarkerConfigurer");
			if (freeMarkerConfigurer != null) {
				configuration = freeMarkerConfigurer.getConfiguration();
			}else{
				ExceptionUtils.throwRuntimeException("spring has not freemarkerConfigurer");
			}
		}
	}
	
	/**
	 * 解析模板文件
	 * 
	 * @param templateFile
	 *            字符串文件
	 * @param model
	 *            数据
	 * @return 解析后内容
	 */
	public static String processFile(String templateFile, Map<String, ?> model) throws IOException, TemplateException {
		Assert.notNull(templateFile, "templateFile 不能为空");
		Assert.notNull(model, "model 不能为空");
		check();
		StringWriter out = new StringWriter();
		configuration.getTemplate(templateFile).process(model, out);
		return out.toString();
	}

	/**
	 * 解析模板字符串
	 * 
	 * @param templateString
	 *            模板字符串
	 * @param model
	 *            数据
	 * @return 解析后内容
	 */
	public static String processString(String templateString, Map<String, ?> model) throws IOException, TemplateException {
		Assert.notNull(templateString, "templateString 不能为空");
		Assert.notNull(model, "model 不能为空");
		check();
		StringWriter out = new StringWriter();
		new Template("template",new StringReader(templateString), configuration).process(model, out);
		return out.toString();
	}


}